import 'package:dio/dio.dart';
import '../models/news_item.dart';

/// 新闻服务（使用Dio进行网络请求）
class NewsService {
  final Dio _dio = Dio(
    BaseOptions(
      baseUrl: 'https://jsonplaceholder.typicode.com',
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 10),
      headers: {'User-Agent': 'Flutter App', 'Accept': 'application/json'},
    ),
  );

  /// 获取新闻列表
  Future<List<NewsItem>> fetchNews() async {
    try {
      // 添加重试机制
      for (int attempt = 0; attempt < 3; attempt++) {
        try {
          final response = await _dio.get('/posts?_limit=20');

          if (response.statusCode == 200) {
            final List<dynamic> data = response.data;
            return data.map((json) {
              return NewsItem.fromJson({
                'id': json['id'],
                'title': json['title'],
                'summary': json['body'].toString().substring(0, 50) + '...',
                'content': json['body'],
                'category': json['id'] % 3 == 0
                    ? '科技'
                    : json['id'] % 3 == 1
                    ? '财经'
                    : '生活',
              });
            }).toList();
          }
        } catch (e) {
          if (attempt == 2) rethrow; // 最后一次尝试失败，抛出异常
          await Future.delayed(Duration(seconds: 1)); // 等待1秒后重试
        }
      }
      throw Exception('加载失败');
    } catch (e) {
      if (e is DioException) {
        switch (e.type) {
          case DioExceptionType.connectionTimeout:
            throw Exception('连接超时，请检查网络连接');
          case DioExceptionType.receiveTimeout:
            throw Exception('接收超时，请稍后重试');
          case DioExceptionType.badResponse:
            throw Exception('服务器错误: ${e.response?.statusCode}');
          case DioExceptionType.cancel:
            throw Exception('请求已取消');
          case DioExceptionType.connectionError:
            throw Exception('网络连接错误，请检查网络');
          default:
            throw Exception('网络错误: ${e.message}');
        }
      }
      throw Exception('网络错误: $e');
    }
  }

  /// 获取新闻详情
  Future<NewsItem> fetchNewsDetail(String id) async {
    try {
      final response = await _dio.get('/posts/$id');

      if (response.statusCode == 200) {
        final json = response.data;
        return NewsItem.fromJson({
          'id': json['id'],
          'title': json['title'],
          'summary': json['body'],
          'content': json['body'],
          'category': int.parse(id) % 3 == 0
              ? '科技'
              : int.parse(id) % 3 == 1
              ? '财经'
              : '生活',
        });
      } else {
        throw Exception('加载失败');
      }
    } catch (e) {
      if (e is DioException) {
        switch (e.type) {
          case DioExceptionType.connectionTimeout:
            throw Exception('连接超时，请检查网络连接');
          case DioExceptionType.receiveTimeout:
            throw Exception('接收超时，请稍后重试');
          case DioExceptionType.badResponse:
            throw Exception('服务器错误: ${e.response?.statusCode}');
          case DioExceptionType.cancel:
            throw Exception('请求已取消');
          case DioExceptionType.connectionError:
            throw Exception('网络连接错误，请检查网络');
          default:
            throw Exception('网络错误: ${e.message}');
        }
      }
      throw Exception('网络错误: $e');
    }
  }

  /// 搜索新闻
  Future<List<NewsItem>> searchNews(String query) async {
    try {
      final response = await _dio.get('/posts?_limit=50');

      if (response.statusCode == 200) {
        final List<dynamic> data = response.data;
        final allNews = data.map((json) {
          return NewsItem.fromJson({
            'id': json['id'],
            'title': json['title'],
            'summary': json['body'].toString().substring(0, 50) + '...',
            'content': json['body'],
            'category': json['id'] % 3 == 0
                ? '科技'
                : json['id'] % 3 == 1
                ? '财经'
                : '生活',
          });
        }).toList();

        // 过滤包含查询关键词的新闻
        return allNews.where((news) {
          return news.title.toLowerCase().contains(query.toLowerCase()) || news.summary.toLowerCase().contains(query.toLowerCase());
        }).toList();
      } else {
        throw Exception('搜索失败');
      }
    } catch (e) {
      if (e is DioException) {
        switch (e.type) {
          case DioExceptionType.connectionTimeout:
            throw Exception('连接超时，请检查网络连接');
          case DioExceptionType.receiveTimeout:
            throw Exception('接收超时，请稍后重试');
          case DioExceptionType.badResponse:
            throw Exception('服务器错误: ${e.response?.statusCode}');
          case DioExceptionType.cancel:
            throw Exception('请求已取消');
          case DioExceptionType.connectionError:
            throw Exception('网络连接错误，请检查网络');
          default:
            throw Exception('网络错误: ${e.message}');
        }
      }
      throw Exception('网络错误: $e');
    }
  }
}
